package com.sqx.modules.app.controller.app;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.annotation.LoginUser;
import com.sqx.modules.app.dao.BlockAndUserDao;
import com.sqx.modules.app.entity.App;
import com.sqx.modules.app.entity.BlockAndUser;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.dto.UserDTO;
import com.sqx.modules.app.service.AppService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.utils.CustomBeanUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app/user")
@Api(value = "APP管理", tags = {"APP管理"})
public class AppController {

    @Autowired
    private UserService userService;
    @Autowired
    private AppService appService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private BlockAndUserDao blockAndUserDao;

    @Login
    @PostMapping("/updateSendMsg")
    @ApiOperation("修改是否接受消息推送")
    public Result updateSendMsg(@LoginUser UserEntity user, @ApiParam(value = "是否推送消息") Integer isSendMsg) {
        user.setIsSendMsg(isSendMsg);
        userService.updateById(user);
        return Result.success();
    }


    @Login
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端修改密码")
    public Result updatePwd(@LoginUser UserEntity user, @ApiParam(value = "新密码") String pwd, @ApiParam(value = "旧密码") String oldPwd) {
        if (!user.getPassword().equals(DigestUtils.sha256Hex(oldPwd))) {
            return Result.error("原始密码不正确！");
        }
        if (pwd.equals(oldPwd)) {
            return Result.error("新密码不能与旧密码相同！");
        }
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        user.setPassword(new Sha256Hash(pwd, salt).toHex());
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updatePhone", method = RequestMethod.POST)
    @ApiOperation("用户端换绑手机号")
    @ResponseBody
    public Result updatePhone(@ApiParam(value = "用户id") @RequestAttribute("userId") Long userId,
                              @ApiParam(value = "手机号") @RequestParam String phone,
                              @ApiParam(value = "验证码") @RequestParam String msg) {
        return userService.updatePhone(phone, msg, userId);
    }

    @Login
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ApiOperation("用户修改个人信息")
    @ResponseBody
    public Result updateUser(@RequestBody UserDTO userDTO, @ApiParam(value = "用户id") @RequestAttribute("userId") Long userId) {
        UserEntity user = userService.getById(userId);
        if (user == null){
            return Result.error("用户不存在，请检查");
        }
        CustomBeanUtils.copyNonNullProperties(userDTO, user, String.valueOf(user.getBalance()));
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateUserImageUrl", method = RequestMethod.POST)
    @ApiOperation("用户修改头像")
    @ResponseBody
    public Result updateUserImageUrl(@LoginUser UserEntity user, @ApiParam(value = "头像") String avatar) {
        user.setAvatar(avatar);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateUserName", method = RequestMethod.POST)
    @ApiOperation("用户修改昵称")
    @ResponseBody
    public Result updateUserName(@LoginUser UserEntity user, @ApiParam(value = "用户修改昵称") String userName) {
        user.setUserName(userName);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/selectUserById", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@LoginUser UserEntity user) {

        userService.updateById(user);
        return Result.success().put("data", user);
    }


    @RequestMapping(value = "/selectNewApp", method = RequestMethod.GET)
    @ApiOperation("升级检测")
    @ResponseBody
    public Result selectNewApp() {
        return Result.success().put("data", appService.selectNewApp());
    }

    @GetMapping(value = "/updateClientId")
    @ApiOperation("绑定ClientId")
    @ResponseBody
    @Login
    public Result updateClientId(@ApiParam(value = "app推送id") String clientId, @ApiParam(value = "用户id") @RequestAttribute("userId") Long userId) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userId);
        userEntity.setClientid(clientId);
        userService.updateById(userEntity);
        return Result.success();
    }

    @GetMapping("/selectUserByUserId")
    @ApiOperation("查看用户信息")
    @ResponseBody
    @Login
    public Result selectUserByUserId(@LoginUser UserEntity user, @ApiParam(value = "用户id") @RequestAttribute("userId") Long userId) {
        return userService.selectUserByUserId(userId, user.getUserId());
    }

    @ApiOperation("查看用户头像，用户名")
    @GetMapping("/selectUserInfoByUserId")
    public Result selectUserInfoByUserId(@ApiParam(value = "用户id") Long userId) {
        UserEntity userEntity = userService.getById(userId);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userId", userEntity.getUserId());
        hashMap.put("userName", userEntity.getUserName());
        hashMap.put("avatar", userEntity.getAvatar());
        return Result.success().put("data", hashMap);

    }

    @Login
    @ApiOperation("拉黑用户")
    @PostMapping("/addToBlacklist")
    public Result addToBlacklist(@ApiParam(value = "用户id") @RequestAttribute Long userId,
                                 @ApiParam(value = "拉黑用户id") Long blockUserId) {
        if (userId.equals(blockUserId)) {
            return Result.error("不能拉黑自己");
        }
        int count = blockAndUserDao.selectCount(new QueryWrapper<BlockAndUser>()
                .eq("user_id", userId)
                .eq("block_user_id", blockUserId));
        if (count > 0) {
            return Result.error("已经拉黑过了");
        }
        BlockAndUser blockAndUser = new BlockAndUser();
        blockAndUser.setUserId(userId);
        blockAndUser.setBlockUserId(blockUserId);
        blockAndUser.setBlockTime(LocalDateTime.now());
        blockAndUserDao.insert(blockAndUser);
        return Result.success();
    }


    @Login
    @ApiOperation("用户查看拉黑用户的列表")
    @GetMapping("/selectBlacklist")
    public Result selectBlacklist(@ApiParam(value = "用户id") @RequestAttribute Long userId,
                                  @ApiParam(value = "用户名") String userName,
                                  @ApiParam(value = "页码") Integer page,
                                  @ApiParam(value = "条数") Integer limit) {
        IPage<BlockAndUser> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<BlockAndUser> blockAndUserIPage = blockAndUserDao.selectPageByUserId(pages, userName, userId);
        return Result.success().put("data", blockAndUserIPage);
    }

    @Login
    @ApiOperation("用户解除拉黑用户")
    @PostMapping("/deleteToBlacklist")
    public Result deleteToBlacklist(@ApiParam(value = "用户id") @RequestAttribute Long userId,
                                    @ApiParam(value = "拉黑方id") Long byUserId,
                                    @ApiParam(value = "拉黑id") Long id) {
        if (byUserId != null) {
            BlockAndUser blockAndUser = blockAndUserDao.selectOne(new QueryWrapper<BlockAndUser>()
                    .eq("user_id", userId)
                    .eq("block_user_id", byUserId));
            if (blockAndUser != null) {
                blockAndUserDao.deleteById(blockAndUser.getId());
                return Result.success();
            }
        } else {
            BlockAndUser blockAndUser = blockAndUserDao.selectById(id);
            if (blockAndUser.getUserId().equals(userId)) {
                blockAndUserDao.deleteById(id);
                return Result.success();
            } else {
                return Result.error("你没有权限");
            }
        }
        return Result.error("解除失败，请重试");
    }

    @Login
    @ApiOperation("查看自己是否被拉黑")
    @GetMapping("/selectBlackByUserId")
    public Result selectBlackByUserId(@ApiParam(value = "用户id") @RequestAttribute Long userId,
                                      @ApiParam(value = "被拉黑用户id") Long byUserId) {
        BlockAndUser blockAndUser = blockAndUserDao.selectOne(new QueryWrapper<BlockAndUser>()
                .eq("user_id", byUserId)
                .eq("block_user_id", userId));
        if (blockAndUser != null) {
            return Result.error("您已被拉黑,暂不能查看");
        }else{
            BlockAndUser blockAndUsers = blockAndUserDao.selectOne(new QueryWrapper<BlockAndUser>()
                    .eq("user_id", userId)
                    .eq("block_user_id", byUserId));
            if (blockAndUsers != null){
                return Result.error("对方已被您拉黑");
            }
        }
        return Result.success();
    }

    @Login
    @ApiOperation("查看自己是否拉黑对方")
    @GetMapping("/selectByBlockUserId")
    public Result selectByBlockUserId(@ApiParam(value = "用户id") @RequestAttribute Long userId,
                                      @ApiParam(value = "被拉黑用户id") Long byUserId) {
        BlockAndUser blockAndUser = blockAndUserDao.selectOne(new QueryWrapper<BlockAndUser>()
                .eq("user_id", userId)
                .eq("block_user_id", byUserId));
        if (blockAndUser != null) {
            return Result.error("您已被拉黑,暂不能查看");
        }
        return Result.success();
    }
}
